package com.googlecode.klenwell.playndev.core;

import static playn.core.PlayN.graphics;

import java.util.LinkedList;

import org.jbox2d.common.Vec2;

import com.google.common.collect.Lists;

import playn.core.CanvasImage;
import playn.core.Color;
import playn.core.Font;
import playn.core.GroupLayer;
import playn.core.ImageLayer;
import playn.core.PlayN;
import playn.core.TextFormat;
import playn.core.TextLayout;

public class GraphicsApi {
    
    // log fields
    public static Integer logDisplayLength = 5;
    public static Integer logFontSize = 12;
    public static Vec2 logScreenPos = new Vec2(5,5);
    private static Font logFont = graphics().createFont("Courier", Font.Style.BOLD, logFontSize);
    private static LinkedList<String> logMessages = Lists.newLinkedList();
    private static Integer logCount = 0;
    private static Integer logColor = Color.rgb(255, 255, 255);
    private static Integer logOddColor = Color.rgb(64, 255, 64);
    private static TextFormat logFormat = new TextFormat().withFont(logFont).withTextColor(logColor);
    private static TextFormat logOddFormat = new TextFormat().withFont(logFont).withTextColor(logOddColor);
    

	public static int screenCenterX() {
		return (int) Math.round(graphics().width() / 2.0);
	}

	public static int screenCenterY() {
		return (int) Math.round(graphics().height() / 2.0);
	}

	public static int worldToScreenX(int x) {
		return screenCenterX() + x;
	}

	public static int worldToScreenY(int y) {
		return screenCenterY() - y;
	}
	
	public static void log(Object object) {
	    String message = object.toString();
	    PlayN.log().info(message);
	    logMessages.addFirst(message);
	}
	
	public static void displayLog() {
	    GroupLayer logLayer = graphics().createGroupLayer();
	    
	    // generate log message images
	    int logSize = (logMessages.size() >= logDisplayLength) ? logDisplayLength : logMessages.size();
	    logCount = 0;
	    
	    for (int n=0; n<logSize; n++) {
	        logCount++;
	        String message = logMessages.get(n);
	        ImageLayer messageImage = generateLogMessageImageLayer(message);
	        Number screenY = logScreenPos.y + (n * (logFontSize + 4));
	        messageImage.transform().translate(logScreenPos.x, screenY.floatValue());
	        logLayer.add(messageImage);
	    }
	    
	    graphics().rootLayer().add(logLayer);
	}
	
	

    /*
	 * Support Methods
	 */
	private static ImageLayer generateLogMessageImageLayer(String message) {
	    TextFormat logFormat_ = (logCount % 2 == 0) ? logFormat : logOddFormat;
	    
	    ImageLayer imageLayer = graphics().createImageLayer();
        TextLayout layout = graphics().layoutText(message, logFormat_);
        CanvasImage logImage = graphics().createImage(graphics().width(), logFontSize + 4);
        logImage.canvas().drawText(layout, 0, 0);
        imageLayer.setImage(logImage);
        return imageLayer;
    }
}
